package annotation.test;

import annotation.ClassAnnotation;

import java.io.File;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Author Jun jie Yi
 * @Date 2022/3/2 16:57
 */
public class GetFileName {

    public static void main(String[] args) {
        //表示一个文件路径src/annotation/test/GetFileName.java
        List<String> filesName = getFilesName("/annotation/test");
        for (String className : filesName) {
            try {
                Class clazz = Class.forName(className);
                //因为注解是作用于类上面的，所以可以通过isAnnotationPresent来判断是否是一个具有指定注解的类
                if (clazz.isAnnotationPresent(ClassAnnotation.class)) {
                    System.out.println("This is a class with annotation ClassAnnotation!");
                    //通过getAnnotation可以获取注解对象
                    ClassAnnotation annotation = (ClassAnnotation) clazz.getAnnotation(ClassAnnotation.class);
                    if (null != annotation) {
                        System.out.println("BeanName = " + annotation.name());
                        System.out.println("BeanVersion = " + annotation.version());
                    } else {
                        System.out.println("the annotation that we get is null");
                    }
                } else {
                    System.out.println("This is not the class that with ClassAnnotation");
                }
            } catch (ClassNotFoundException e) {
                System.out.println(className + " 不是java文件的全类名");
            }
        }
    }

    public synchronized static List<String> getFilesName(String clientBase) {
        String path = "src" + clientBase;
        List<String> filesName = new CopyOnWriteArrayList<>();
        getFiles(path, filesName);
        return filesName.parallelStream().map(e -> e.substring(4, e.length() - 5).replaceAll("\\\\", ".")).collect(Collectors.toList());
    }

    /**
     * 递归获取某路径下的所有文件，文件夹，并输出
     */
    private static void getFiles(String clientBase, List<String> filesName) {

        File file = new File(clientBase);
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果还是文件夹 递归获取里面的文件 文件夹
                if (files[i].isDirectory()) {
                    //System.out.println("目录：" + files[i].getPath());
                    //继续读取文件夹里面的所有文件
                    getFiles(files[i].getPath(), filesName);
                } else {
                    filesName.add(files[i].getPath());
                    //System.out.println("文件：" + files[i].getPath());
                }
            }
        } else {
            filesName.add(file.getPath());
            //System.out.println("文件：" + file.getPath());
        }
    }
}
